package com.example.weather_forecast;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;

import androidx.core.app.NotificationCompat;

public class NotificationReceiver extends BroadcastReceiver {

    // 通知动作常量
    public static final String ACTION_DAILY_FORECAST = "com.example.weatherforecast.ACTION_DAILY_FORECAST";
    public static final String ACTION_WEATHER_ALERT = "com.example.weatherforecast.ACTION_WEATHER_ALERT";

    // 通知额外数据常量
    public static final String EXTRA_SOUND = "extra_sound";
    public static final String EXTRA_VIBRATION = "extra_vibration";
    public static final String EXTRA_ALERT_TYPE = "extra_alert_type";

    // 通知渠道ID
    private static final String CHANNEL_ID_DAILY = "weather_daily_channel";
    private static final String CHANNEL_ID_ALERT = "weather_alert_channel";

    // 通知ID
    private static final int NOTIFICATION_ID_DAILY = 1001;
    private static final int NOTIFICATION_ID_ALERT = 2001;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (action != null) {
            switch (action) {
                case ACTION_DAILY_FORECAST:
                    handleDailyForecast(context, intent);
                    break;
                case ACTION_WEATHER_ALERT:
                    handleWeatherAlert(context, intent);
                    break;
            }
        }
    }

    private void handleDailyForecast(Context context, Intent intent) {
        boolean enableSound = intent.getBooleanExtra(EXTRA_SOUND, true);
        boolean enableVibration = intent.getBooleanExtra(EXTRA_VIBRATION, true);

        // 创建通知渠道（仅在Android O及以上版本需要）
        createNotificationChannel(context, CHANNEL_ID_DAILY, "每日天气预报", NotificationManager.IMPORTANCE_DEFAULT);

        // 获取当前天气数据
        // 注意：在实际应用中，这里应该从天气服务或本地数据库获取真实的天气数据
        // 这里仅使用假数据作为示例
        String weatherInfo = "今日天气：晴，气温18°C ~ 26°C，风力3级";

        // 创建打开应用的意图
        Intent mainIntent = new Intent(context, MainActivity.class);
        mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID_DAILY)
                .setSmallIcon(R.drawable.ic_notification) // 确保在drawable中有这个图标
                .setContentTitle("每日天气预报")
                .setContentText(weatherInfo)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(weatherInfo))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        // 设置声音
        if (enableSound) {
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            builder.setSound(defaultSoundUri);
        }

        // 设置振动
        if (enableVibration) {
            long[] vibrationPattern = {0, 300, 200, 300};
            builder.setVibrate(vibrationPattern);
        }

        // 显示通知
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.notify(NOTIFICATION_ID_DAILY, builder.build());
        }
    }

    private void handleWeatherAlert(Context context, Intent intent) {
        boolean enableSound = intent.getBooleanExtra(EXTRA_SOUND, true);
        boolean enableVibration = intent.getBooleanExtra(EXTRA_VIBRATION, true);
        String alertType = intent.getStringExtra(EXTRA_ALERT_TYPE);

        // 创建通知渠道（仅在Android O及以上版本需要）
        createNotificationChannel(context, CHANNEL_ID_ALERT, "天气预警", NotificationManager.IMPORTANCE_HIGH);

        // 根据预警类型构建预警信息
        String alertTitle = "天气预警";
        String alertContent = "有一个天气预警需要您注意！";

        if (alertType != null) {
            switch (alertType) {
                case "rain":
                    alertTitle = "暴雨预警";
                    alertContent = "预计未来24小时内将有强降雨，请注意防范。";
                    break;
                case "typhoon":
                    alertTitle = "台风预警";
                    alertContent = "台风即将登陆，请做好防范准备。";
                    break;
                case "heat":
                    alertTitle = "高温预警";
                    alertContent = "预计未来几天将出现高温天气，请注意防暑降温。";
                    break;
                case "cold":
                    alertTitle = "寒潮预警";
                    alertContent = "寒潮即将来袭，气温将大幅下降，请注意保暖。";
                    break;
            }
        }

        // 创建打开应用的意图
        Intent mainIntent = new Intent(context, MainActivity.class);
        mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID_ALERT)
                .setSmallIcon(R.drawable.ic_alert) // 确保在drawable中有这个图标
                .setContentTitle(alertTitle)
                .setContentText(alertContent)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(alertContent))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        // 设置声音
        if (enableSound) {
            Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            if (alarmSound == null) {
                alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
            builder.setSound(alarmSound);
        }

        // 设置振动
        if (enableVibration) {
            long[] vibrationPattern = {0, 500, 200, 500, 200, 500};
            builder.setVibrate(vibrationPattern);
        }

        // 显示通知
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            // 对于预警通知，使用不同的ID，以免覆盖每日预报通知
            int alertId = NOTIFICATION_ID_ALERT;
            if (alertType != null) {
                // 不同类型的预警使用不同的ID，避免相互覆盖
                switch (alertType) {
                    case "rain":
                        alertId += 1;
                        break;
                    case "typhoon":
                        alertId += 2;
                        break;
                    case "heat":
                        alertId += 3;
                        break;
                    case "cold":
                        alertId += 4;
                        break;
                }
            }
            notificationManager.notify(alertId, builder.build());
        }
    }

    private void createNotificationChannel(Context context, String channelId, String channelName, int importance) {
        // 创建通知渠道仅适用于Android O及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    channelId,
                    channelName,
                    importance
            );

            // 配置通知渠道
            channel.setDescription("天气应用通知渠道：" + channelName);

            // 注册通知渠道
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
}